<template>
    <view class="login" @click="">
        <!-- 当设置 "navigationStyle":"custom" 取消原生导航栏后，由于窗体为沉浸式，占据了状态栏位置。此时可以使用一个高度为 var(--status-bar-height) 的 view 放在页面顶部，避免页面内容出现在状态栏。 -->
        <view class="bar-height"></view>
        <view class="logo"></view>
        <view class="login-text">{{showType}}</view>
        <!-- 登录账号 -->
        <view v-show="showType == '登录账号'" class="myforms">
            <uni-forms
                 :model="formData1" 
                 ref="form1" 
                 :rules="rules1" 
                 validateTrigger="submit" 
                 label-width="0px"
                 err-show-type='none'
             >
                 <uni-forms-item name="username">
                     <uni-easyinput 
                         type="text" 
                         v-model="formData1.username" 
                         prefixIcon="contact"
                         placeholder="请输入用户名" 
                     />
                 </uni-forms-item>
                 <uni-forms-item name="password">
                     <uni-easyinput 
                        type="password" 
                        v-model="formData1.password" 
                        prefixIcon="info" 
                        placeholder="请输入密码" 
                    />
                 </uni-forms-item>
             </uni-forms>
            <button  @click="submit1">登录</button>
            <view class="tips">
                <view @click="showType = '注册账号';refreshImgVC()">注册账号</view>
                <!-- <view @click="showType = '忘记密码'">忘记密码</view> -->
            </view>
        </view>
        
        <!-- 注册账号 -->
        <view v-show="showType == '注册账号'" class="myforms">
            <uni-forms
                 :model="formData2" 
                 ref="form2" 
                 :rules="rules2" 
                 validateTrigger="submit" 
                 label-width="140rpx"
                 err-show-type='none'
             >
                <uni-forms-item 
                    name="customerName"
                    label="公司名称"
                >
                    <uni-easyinput 
                        type="text" 
                        v-model="formData2.customerName" 
                        placeholder="请输入公司名称" 
                    />
                </uni-forms-item>
                <uni-forms-item 
                    name="position"
                    label="岗位"
                >
                    <uni-easyinput 
                        type="text" 
                        v-model="formData2.position" 
                        placeholder="请输入岗位" 
                    />
                </uni-forms-item>
                <uni-forms-item 
                    name="name"
                    label="姓名"
                >
                    <uni-easyinput 
                        type="text" 
                        v-model="formData2.name" 
                        placeholder="请输入姓名" 
                    />
                </uni-forms-item>
                
                 <uni-forms-item 
                    name="username"
                    label="用户名"
                >
                     <uni-easyinput 
                         type="text" 
                         v-model="formData2.username" 
                         placeholder="请输入用户名" 
                     />
                 </uni-forms-item>
                 <uni-forms-item 
                    name="password"
                    label="密码"
                >
                     <uni-easyinput 
                        type="password" 
                        v-model="formData2.password" 
                        placeholder="请输入密码" 
                    />
                 </uni-forms-item>
                 <uni-forms-item 
                    name="confirmPassword"
                    label="确认密码"
                >
                     <uni-easyinput 
                        type="password" 
                        v-model="formData2.confirmPassword" 
                        placeholder="请输入确认密码" 
                    />
                 </uni-forms-item>
                 <uni-forms-item
                     name="imgText"
                     label="图形验证"
                 >
                      <view class="img-text">
                         <uni-easyinput
                             type="text" 
                             v-model="formData2.imgText" 
                             placeholder="请输入图形验证" 
                         />
                         <image
                             scaleToFill
                             class="avatar" 
                             :src="imgVC"
                             :draggable="false"
                             @click="refreshImgVC"
                         >
                         </image>
                      </view>
                  </uni-forms-item>
                 <uni-forms-item 
                    name="phone"
                    label="手机号"
                >
                     <view class="phone-vc">
                        <uni-easyinput
                            type="number" 
                            v-model="formData2.phone" 
                            maxlength="11"
                            placeholder="请输入手机号" 
                        />
                        <!-- <button
                            type="default"
                            :disabled="vcText != '验证码'"
                            @click="getVc(formData2.phone)"
                        >
                            {{ vcText }}
                        </button> -->
                        <!-- <button
                            type="default"
                            :disabled="vcText != '验证码'"
                            @click="openMoveVerifyPopup"
                        >
                            {{ vcText }}
                        </button> -->
                        <button
                            type="default"
                            :disabled="vcText != '验证码'"
                            @click="confirmImgVC"
                        >
                            {{ vcText }}
                        </button>
                     </view>
                 </uni-forms-item>
                 <uni-popup ref="popup" type="center">
                     <move-verify :style="{ marginTop: '0rpx'} " @vertify='vertifyResult'></move-verify>
                 </uni-popup>
                 <uni-forms-item 
                    name="vc"
                    label="验证码"
                >
                     <uni-easyinput 
                        type="number" 
                        v-model="formData2.vc" 
                        placeholder="请输入验证码" 
                    />
                 </uni-forms-item>
             </uni-forms>
            <button  @click="submit2">注册</button>
            <view class="tips">
                <view @click="showType = '登录账号'">登录账号</view>
                <!-- <view @click="showType = '忘记密码'">忘记密码</view> -->
            </view>
        </view>
        <!-- 忘记密码 -->
        <view v-show="showType == '忘记密码'" class="myforms">
            <uni-forms
                 :model="formData3" 
                 ref="form3" 
                 :rules="rules3" 
                 validateTrigger="submit" 
                 label-width="0px"
                 err-show-type='none'
             >
                 <uni-forms-item name="username">
                     <uni-easyinput 
                         type="text" 
                         v-model="formData3.username" 
                         prefixIcon="contact"
                         placeholder="请输入用户名" 
                     />
                 </uni-forms-item>
                 <uni-forms-item name="password">
                     <uni-easyinput 
                        type="password" 
                        v-model="formData3.password" 
                        prefixIcon="info" 
                        placeholder="请输入密码" 
                    />
                 </uni-forms-item>
             </uni-forms>
            <button  @click="submit3">确认</button>
            <view class="tips">
                <view @click="showType = '登录账号'">登录账号</view>
                <view @click="showType = '注册账号'">注册账号</view>
            </view>
        </view>
    </view>
</template>

<script lang="ts" setup>
    import { onLoad, onShow, onHide, onReady, onUnload } from '@dcloudio/uni-app'
    import { markRaw, onBeforeUnmount, reactive, ref } from 'vue'
    import type { Ref, Raw } from 'vue'
    import { loginApi, smsSendVcApi, userRegisterApi, captchaImgApi } from '@/apis/index'
    import { isPhone } from '@/utils/utils'
    /**
     * 展示状态
     * 登录账号, 注册账号, 忘记密码
     * 
     */
    const showType: Ref<string> = ref('登录账号')
    
    let redirectUrl = ''
    onLoad((opt: any) => {
        console.log(opt)
        if (opt.url) {
            redirectUrl = opt.url
        }
    })
    
    // 如果需要使用 validateFunction 自定义校验规则,则不能采用 uni-forms 的 rules 属性来配置校验规则，这时候需要通过ref，在onReady生命周期调用组件的setRules方法绑定验证规则
    onReady(() => {
        form2.value.setRules(rules2)
    })
    const routerPush = () => {
        uni.navigateTo({
            url: '/pages/mine/mine'
        })
    }
    
    const formData1: any = reactive({
        // username: 'test',
        // password: '123456',
        username: '',
        password: '',
        phone: '',
        code: '',
        Company: '',
    })
    const form1: Ref<any> = ref(null)
    const rules1: any = reactive({
        username: {
            rules: [
                {
                    required: true,
                    errorMessage: '请输入用户名',
                },
                // {
                //     minLength: 3,
                //     maxLength: 5,
                //     errorMessage: '账号长度在 {minLength} 到 {maxLength} 个字符',
                // },
                // {
                //     validateFunction:function(rule, value, data, callback){
                //         if (value.length < 2) {
                //             callback('请至少勾选两个兴趣爱好')
                //         }
                //         return true
                //     }
                // }
            ],
        },
        password: {
            rules: [
                {
                    required: true,
                    errorMessage: '请输入密码',
                },
            ],
        }
    })
   
    
    const submit1 = () => {
        console.log(form1.value)
        form1.value.validate().then((res: any) => {
            console.log('表单数据信息：', res);
            // 调接口
            loginApi({
                username: formData1.username,
                password: btoa(formData1.password),
            }).then((res: any) => {
                console.log(res)
                if (res.code == 200) {
                    uni.setStorageSync('token', res.data)
                    console.log(redirectUrl)
                    if (redirectUrl) {
                        uni.reLaunch({
                        	url: redirectUrl
                        });
                    } else {
                        uni.reLaunch({
                        	url: '/pages/index/index'
                        });
                    }
                    
                } else {
                    uni.showToast({
                    	title: res.msg,
                        icon: 'error',
                    	duration: 1500,
                        mask: true,
                    });
                }
            }).catch((err: any) => {
                console.log('err')
            })
            
        }).catch((err: any) =>{
            console.log('表单错误信息：', err);
            uni.showToast({
            	title: err[0].errorMessage,
                icon: 'error',
            	duration: 1500,
                mask: true,
            });
        })
    }
    // 注册账号
    const form2: Ref<any> = ref(null)
    const formData2: any = reactive({
        username: '',
        password: '',
        customerName: '',
        position: '生产工人',
        name: '',
        confirmPassword: '',
        phone: '',
        vc: '',
        imgText: '',
    })
    
    const rules2: any = reactive({
        username: {
            rules: [
                {
                    required: true,
                    errorMessage: '请输入用户名',
                },
            ],
        },
        password: {
            rules: [
                {
                    required: true,
                    errorMessage: '请输入密码',
                },
            ],
        },
        customerName: {
            rules: [
                {
                    required: true,
                    errorMessage: '请输入公司名称',
                },
            ],
        },
        position: {
            rules: [
                {
                    required: true,
                    errorMessage: '请输入岗位',
                },
            ],
        },
        name: {
            rules: [
                {
                    required: true,
                    errorMessage: '请输入姓名',
                },
            ],
        },
        confirmPassword: {
            rules: [
                {
                    required: true,
                    errorMessage: '请输入确认密码',
                },
                {
                    validateFunction:function(rule,value,data,callback){
                        if (value != formData2.password) {
                            callback('两次密码不一致')
                        }
                        return true
                    }
                }
            ],
        },
        phone: {
            rules: [
                {
                    required: true,
                    errorMessage: '请输入手机号',
                },{
                    validateFunction: function(rule, value, data, callback){
                        if (!isPhone(value)) {
                            callback('请输入正确的手机号')
                        }
                        return true
                    }
                }
            ],
        },
        vc: {
            rules: [
                {
                    required: true,
                    errorMessage: '请输入验证码',
                },
            ],
        }
    })
    // 图形验证码
    const imgVC: Ref<any> = ref('')
    const imgVCId: Ref<any> = ref('')
    const refreshImgVC = (() => {
        console.log('获取图形验证码')
        // imgVC.value
        captchaImgApi().then((res: any) => {
            if (res.code == 200) {
                imgVC.value = 'data:image/png;base64,' + res.data.imgBase64
                imgVCId.value = res.data.id
            }
        })
    })
    const confirmImgVC = (() => {
        console.log('调接口确认图形是否正确')
        if (!formData2.imgText) {
            uni.showToast({
            	title: '请输入图形验证',
                icon: 'error',
            	duration: 1500,
                mask: true,
            });
        } else {
            getVc(formData2.phone)
            // captchaCheckApi({
            //     id: imgVCId.value,
            //     text: formData2.imgText,
            // }).then((res: any) => {
            //     if (res.code == 200) {
            //         getVc(formData2.phone)
            //     } else {
            //         uni.showToast({
            //         	title: '图形验证校验失败',
            //             icon: 'error',
            //         	duration: 1500,
            //             mask: true,
            //         });
            //     }
            // }).catch((err: any) => {
            //     uni.showToast({
            //     	title: '图形验证校验失败',
            //         icon: 'error',
            //     	duration: 1500,
            //         mask: true,
            //     });
            // })
        }
        
    })
    
    /**
     * 滑动验证
     */
    
    const popup: Ref<any> = ref(null)
    const openMoveVerifyPopup = (() => {
        // 通过组件定义的ref调用uni-popup方法 ,如果传入参数 ，type 属性将失效 ，仅支持 ['top','left','bottom','right','center']
        popup.value.open()
    })
    
    // const vertify: Ref<boolean> = ref(false)
    const vertifyResult = ((val: boolean) => {
        // vertify.value = val
        console.log(val)
        if (val) {
            popup.value.close()
            getVc(formData2.phone)
        }
    })
    
    const vcText: Ref<string> = ref('验证码')
    const vcNum: Ref<number> = ref(10)
    const vcInterval: Ref<any> = ref('')
    const getVc = ((val: number) => {
        if (!isPhone(val)) {
            uni.showToast({
            	title: '请输入正确的手机号',
                icon: 'error',
            	duration: 1500,
                mask: true,
            });
        } else {
            vcNum.value = 10
            vcText.value = vcNum.value + 's'
            vcInterval.value = setInterval(() => {
                vcNum.value--
                vcText.value = vcNum.value + 's'
                if (vcNum.value <= 0) {
                    clearInterval(vcInterval.value)
                    vcText.value = '验证码'
                }
            }, 1000)
            smsSendVcApi({
                mobile: val,
                type: 2,
                captchaImgVO: {
                    id: imgVCId.value,
                    text: formData2.imgText,
                },
            }).then((res: any) => {
                if (res.code == 200) {
                    uni.showToast({
                    	title: res.msg,
                        icon: 'none',
                    	duration: 1500,
                        mask: true,
                    });
                } else {
                    uni.showToast({
                    	title: res.msg,
                        icon: 'error',
                    	duration: 1500,
                        mask: true,
                    });
                }
            })
        }
    })
    
    onUnload(() => {
        if (vcInterval.value) {
            clearInterval(vcInterval.value)
        }
    })
    const submit2 = () => {
        console.log(form2.value)
        form2.value.validate().then((res1: any) => {
            console.log('表单数据信息：', res1);
            // 调接口
            let formd2: any = JSON.parse(JSON.stringify(formData2))
            formd2.confirmPassword = btoa(formData2.confirmPassword)
            formd2.password = btoa(formData2.password)
            userRegisterApi(formd2).then((res2: any) => {
                console.log(res2)
                if (res2.code == 200) {
                    uni.showModal({
                        showCancel: false,
                    	title: '提示',
                    	content: res2.msg,
                    	success: function (res) {
                            showType.value = '登录账号'
                    		// if (res.confirm) {
                    		// 	console.log('用户点击确定');
                    		// } else if (res.cancel) {
                    		// 	console.log('用户点击取消');
                    		// }
                    	}
                    });
                } else {
                    uni.showToast({
                    	title: res2.msg,
                        icon: 'error',
                    	duration: 1500,
                        mask: true,
                    });
                }
            })
            
        }).catch((err: any) =>{
            console.log('表单错误信息：', err);
            console.log(err);
            uni.showToast({
            	title: err[0].errorMessage,
                icon: 'error',
            	duration: 1500,
                mask: true,
            });
        })
    }
    
    // 忘记密码
    const form3: Ref<any> = ref(null)
    const formData3: any = reactive({
        username: '',
        password: '',
        phone: '',
        code: '',
        Company: '',
    })
    const rules3: any = reactive({
        username: {
            rules: [
                {
                    required: true,
                    errorMessage: '请输入用户名',
                },
            ],
        },
        password: {
            rules: [
                {
                    required: true,
                    errorMessage: '请输入密码',
                },
            ],
        }
    })
    const submit3 = () => {
        console.log(form3.value)
        form3.value.validate().then((res: any) => {
            console.log('表单数据信息：', res);
            uni.showLoading({
                title: '加载中1...',
                mask: true,
            })
            // 调接口
            uni.hideLoading()
            
        }).catch((err: any) =>{
            console.log('表单错误信息：', err);
            uni.showToast({
            	title: err[0].errorMessage,
                icon: 'error',
            	duration: 1500,
                mask: true,
            });
        })
    }
</script>

<style lang="scss" scoped>
    .bar-height {
        width: 100vw;
        height: var(--status-bar-height);
    }
    
    // .login {
    //     width: 100vw;
    //     // height: 100vh;
    //     height: calc(100vh - var(--window-top) - var(--window-bottom)); //var(--window-top) 页面的内容区域距离顶部距离 var(--window-bottom) 页面的内容区域距离底部距离 app不存在，h5有这两个高度
    //     background: url(@/static/login/login-bg.png);
    //     background-size: 100% 100%;
    //     box-sizing: border-box;
    //     padding: 0 60rpx;
    //     // display: flex;
    //     // flex-direction: column;
    //     // align-items: center;
    //     position: absolute;
    // }
    .login::before {
        content: '';
        width: 100vw;
        // height: 100vh;
        height: calc(100vh - var(--window-top) - var(--window-bottom)); //var(--window-top) 页面的内容区域距离顶部距离 var(--window-bottom) 页面的内容区域距离底部距离 app不存在，h5有这两个高度
        background: url(@/static/login/login-bg4.png) 50% 70%/120% 110%;
        // filter: blur(5rpx);
        // background-size: 100% 100%;
        box-sizing: border-box;
        padding: 0 60rpx;
        // display: flex;
        // flex-direction: column;
        // align-items: center;
        position: absolute;
        z-index: -1;
        overflow: hidden;
    }
    .login {
        width: 100vw;
        height: calc(100vh - var(--window-top) - var(--window-bottom)); //var(--window-top) 页面的内容区域距离顶部距离 var(--window-bottom) 页面的内容区域距离底部距离 app不存在，h5有这两个高度
        position: absolute;
    }
    
    .logo {
        width: 140rpx;
        height: 140rpx;
        background: url(@/static/logo.png);
        background-size: 100% 100%;
        margin: 60rpx auto 60rpx;
    }
    .myforms {
        background-color: rgba(255, 255, 255, 0.1);
        padding: 80rpx 40rpx;
        box-sizing: border-box;
        height: 800rpx;
        overflow-x: hidden;
        overflow-y: scroll;
        
    }
    :deep(.myforms .uni-forms-item__label) {
        color: #fff;
    }
    .tips {
        box-sizing: border-box;
        padding: 60rpx 0 0 0;
        display: flex;
        justify-content: space-between;
        color: #fff;
    }
    :deep(.uni-easyinput__content-input) {
        font-size: 30rpx;
    }
    .login-text {
        padding: 20rpx 40rpx;
        color: #fff;
        font-weight: bold;
        text-shadow: 0 0rpx 10rpx #aaaaff;
    }
    .phone-vc {
        display: flex;
        button {
            width: 150rpx;
            height: 74rpx;
            font-size: 30rpx;
        }
    }
    .img-text {
        display: flex;
        image {
            width: 150rpx;
            height: 74rpx;
            font-size: 30rpx;
        }
    }
</style>
